package collaborynth.apod;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

public class RSSObject {
	
	public enum Mode { NO_ASYNC_TASK, NO_DOWNLOADED_DRAWABLE, CORRECT }
    private Mode mode = Mode.NO_ASYNC_TASK;
    private static final String LOG_TAG = "ImageDownloader";
	
    private String pageurl;
	private String imgurl;
	private ImageView imView;
	public Bitmap bm;
	
	RSSObject(){
		imgurl= "http://apod.nasa.gov/apod/";
	}
	
	public void setPageURL(String url){
		pageurl = url;
	}
	
	RSSObject(String url) throws IOException{
		imgurl= "http://apod.nasa.gov/apod/";
		pageurl = url;
	}
	
	public void getImage(){
		new DownloadImageTask().execute(pageurl);
		/*while(){
			
		}*/
		Log.d("IMAGE", imgurl);
	}
	
	public Bitmap getBitmap(){
		return this.bm;
	}
	 /*
     * An InputStream that skips the exact number of bytes provided, unless it reaches EOF.
     */
    static class FlushedInputStream extends FilterInputStream {
        public FlushedInputStream(InputStream inputStream) {
            super(inputStream);
        }

        @Override
        public long skip(long n) throws IOException {
            long totalBytesSkipped = 0L;
            while (totalBytesSkipped < n) {
                long bytesSkipped = in.skip(n - totalBytesSkipped);
                if (bytesSkipped == 0L) {
                    int b = read();
                    if (b < 0) {
                        break;  // we reached EOF
                    } else {
                        bytesSkipped = 1; // we read one byte
                    }
                }
                totalBytesSkipped += bytesSkipped;
            }
            return totalBytesSkipped;
        }
    }

	private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
		String imgloc = "";
        protected Bitmap doInBackground	(String... urls) {
            try {
				imgloc = getImageLocation(urls[0]);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			bm = downloadBitmap(imgurl);
			return bm;
        }
        
        String getImageLocation(String url) throws IOException{
        	Document doc = Jsoup.connect(url).get();
    		Element imageloc = doc.select("a").get(1);
    		imgurl = imgurl + imageloc.attr("href");
    		Log.d("IMAGE", imgurl);
    		return null;
        }
        
        Bitmap downloadBitmap(String url) {
        	Log.d("IMAGE", "Starting Image Download");
            final int IO_BUFFER_SIZE = 4 * 1024;

            // AndroidHttpClient is not allowed to be used from the main thread
            final HttpClient client = (mode == Mode.NO_ASYNC_TASK) ? new DefaultHttpClient() :
                AndroidHttpClient.newInstance("Android");
            final HttpGet getRequest = new HttpGet(url);

            try {
                HttpResponse response = client.execute(getRequest);
                final int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != HttpStatus.SC_OK) {
                    Log.w("ImageDownloader", "Error " + statusCode +
                            " while retrieving bitmap from " + url);
                    return null;
                }

                final HttpEntity entity = response.getEntity();
                if (entity != null) {
                    InputStream inputStream = null;
                    try {
                        inputStream = entity.getContent();
                        // return BitmapFactory.decodeStream(inputStream);
                        // Bug on slow connections, fixed in future release.
                        return BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
                    } finally {
                        if (inputStream != null) {
                            inputStream.close();
                        }
                        entity.consumeContent();
                    }
                }
            } catch (IOException e) {
                getRequest.abort();
                Log.w(LOG_TAG, "I/O error while retrieving bitmap from " + url, e);
            } catch (IllegalStateException e) {
                getRequest.abort();
                Log.w(LOG_TAG, "Incorrect URL: " + url);
            } catch (Exception e) {
                getRequest.abort();
                Log.w(LOG_TAG, "Error while retrieving bitmap from " + url, e);
            } finally {
                if ((client instanceof AndroidHttpClient)) {
                    ((AndroidHttpClient) client).close();
                }
            }
            return null;
        }

        protected void onPostExecute(Bitmap bm) {
            imView.setImageBitmap(bm);
        }
    }
       
}